package com.rc.saas.payment.wxpay.utils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

/**
 * Created by sven on 2018-03-26
 */
public class XmlBuilder {
    /**
     * 将pojo转换为XML字符串
     *
     * @param object
     * @return
     */
    public static String convertToXml(Object object) {
        Writer sw = new StringWriter();
        try {
            // 利用jdk中自带的转换类实现
            JAXBContext context = JAXBContext.newInstance(object.getClass());

            Marshaller marshaller = context.createMarshaller();
            // 格式化xml输出的格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            // 将对象转换成输出流形式的xml
            marshaller.marshal(object, sw);
        } catch (JAXBException e) {
            e.printStackTrace();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sw.toString().replace("standalone=\"yes\"", "");
    }
}
